package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 跟订单相关的定时任务类；处理超时未支付订单与一直派送中的订单
 */
@Slf4j
@Component
public class OrderTask {
    @Autowired
    private OrdersMapper ordersMapper;
    /**
     * 每分钟检查一次是否存在超时订单(下单超过15分钟未支付就代表超时)
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrders(){
        log.info("处理超时订单：{}", DateTimeFormatter.ofPattern("HH:mm:ss").format(LocalDateTime.now()));
        //1拆寻orders表，条件：下单时间小于当前时间减15分钟，并且订单状态为1（待支付）
        //select * from orders where status = 1 and order_time < 当前时间减15分钟
        List<Orders> ordersList =ordersMapper.selectByStatusAndOrderTime(Orders.PENDING_PAYMENT, LocalDateTime.now().minusMinutes(15));
        //2如果查到了数据，代表存在超时订单，需要修改订单状态为“status=6”
        //update orders set status = 6 where status = 1 and order_time < 当前时间减15分钟
        if (ordersList != null && !ordersList.isEmpty()){
                 ordersList.forEach(orders -> {
                     orders.setStatus(Orders.CANCELLED);
                     orders.setCancelReason("订单超时,自动取消");
                     orders.setCancelTime(LocalDateTime.now());
                     ordersMapper.update(orders);
                 });
        }
    }
    /**
     * 每天凌晨1点执行一次，处理处于派送中的订单，如果存在处于派送中的订单，则修改订单状态为“完成”
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processCompletedOrder(){
        log.info("处理处于派送中的订单：{}",DateTimeFormatter.ofPattern("HH:mm:ss").format(LocalDateTime.now()));
        List<Orders> ordersList = ordersMapper.selectByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().minusMinutes(60));
        if (ordersList != null && !ordersList.isEmpty()){
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.COMPLETED);
                orders.setDeliveryTime(LocalDateTime.now().minusMinutes(60));
                ordersMapper.update(orders);
            });
        }
    }
}
